package com.shunbo.convenient.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shunbo.convenient.service.*;
import com.shunbo.convenient.utils.ConvenientResult;
import com.shunbo.convenient.utils.DateUtils;
import com.shunbo.convenient.utils.JsonUtils;
import com.shunbo.convenient.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author weizhuang
 * 订单
 */
@RestController
@RequestMapping("/order")
public class OrdersController {


    @Resource
    private OrdersService ordersService;

    @Resource
    private ProductOrderService productOrderService;

    @Resource
    private ProductService productService;

    @Resource
    private AddressService addressService;
    @Resource
    private CustomerInfoService customerInfoService;
    @Resource
    private LogService logService;
    @Resource
    private BlessingService blessingService;
    @Resource
    private StoreService storeService;


    /**
     * 订单列表
     *
     * @param order 订单
     * @return Result结果集
     */
    @RequestMapping("/list")
    public ConvenientResult getOrderList(@RequestBody Orders order) {
        try {

            System.out.println(order.getPageNo());
            if (order.getPageNo() == null) {
                order.setPageNo(1);
            }
            PageHelper.startPage(order.getPageNo(), 10);
            List<Orders> all;
            if (StringUtils.isEmpty(order.getCreateTime())) {
                all = ordersService.findAll(order);
            } else {
                String createTime = order.getCreateTime();
                String[] str = createTime.split(" - ");
                all = ordersService.findBetween(str[0], str[1], order.getSid() + "");
            }
            for (Orders orders : all
                    ) {
                Double money = 0.0;
                Long id = orders.getId();
                ProductOrder productOrder = new ProductOrder();
                productOrder.setOid(id + "");
                List<ProductOrderResult> productOrderResults = new ArrayList<>();
                List<ProductOrder> all1 = productOrderService.findAll(productOrder);
                for (ProductOrder po : all1
                        ) {
                    if (po.getPid() != null) {
                        Product byId = productService.findById(po.getPid() + "");
                        ProductOrderResult productOrderResult = new ProductOrderResult();
                        productOrderResult.setMoney(byId.getMoney());
                        productOrderResult.setPrice(byId.getPrice());
                        productOrderResult.setName(byId.getName());
                        productOrderResult.setNum(po.getNum());
                        productOrderResult.setImg(byId.getImg());
                        productOrderResults.add(productOrderResult);
                        money += po.getNum() * byId.getMoney();
                    }
                    if (po.getBid() != null) {
                        Blessing byId = blessingService.findById(po.getBid() + "");
                        double v = byId.getMoney();
                        ProductOrderResult productOrderResult = new ProductOrderResult();
                        productOrderResult.setMoney(v);
                        productOrderResult.setPrice(v);
                        productOrderResult.setType(1);
                        productOrderResult.setName(byId.getName());
                        productOrderResult.setNum(po.getNum());
                        productOrderResults.add(productOrderResult);
                        money += po.getNum() * v;
                    }
                }
                Store byId1 = storeService.findById(orders.getSid() + "");
                Address byId = addressService.findById(orders.getAid());
                orders.setCountMoney(money+"");
                orders.setSname(byId1.getName());
                orders.setProductOrderResultsList(productOrderResults);
                orders.setAddress(byId);
            }
            PageInfo<Orders> pageInfo = new PageInfo<>(all);
            Map<String, Object> map = new HashMap<>();
            map.put("orderList", all);
            map.put("pageNo", order.getPageNo());
            map.put("count", pageInfo.getTotal());
            return ConvenientResult.build(200, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 订单列表
     *
     * @param order 订单
     * @return Result结果集
     */
    @RequestMapping("/list1")
    public ConvenientResult getOrderList1(@RequestBody Orders order) {
        try {
            if (order.getPageNo() == null) {
                order.setPageNo(1);
            }
            PageHelper.startPage(order.getPageNo(), 10);
            List<Orders> all;
            if (StringUtils.isEmpty(order.getCreateTime())) {
                all = ordersService.findAll(order);
            } else {
                String createTime = order.getCreateTime();
                String[] str = createTime.split(" - ");
                all = ordersService.findBetween(str[0], str[1], null);
            }
            for (Orders orders : all
                    ) {

                Double money = 0.0;
                Integer count = 0;
                Long id = orders.getId();
                ProductOrder productOrder = new ProductOrder();
                productOrder.setOid(id + "");
                List<ProductOrderResult> productOrderResults = new ArrayList<>();
                List<ProductOrder> all1 = productOrderService.findAll(productOrder);
                for (ProductOrder po : all1
                        ) {
                    if (po.getPid() != null) {
                        Product byId = productService.findById(po.getPid() + "");
                        ProductOrderResult productOrderResult = new ProductOrderResult();
                        productOrderResult.setMoney(byId.getMoney());
                        productOrderResult.setPrice(byId.getPrice());
                        productOrderResult.setName(byId.getName());
                        productOrderResult.setNum(po.getNum());
                        productOrderResult.setImg(byId.getImg());
                        productOrderResult.setType(0);
                        productOrderResults.add(productOrderResult);
                        money += po.getNum() * byId.getMoney();
                        count += po.getNum();
                        orders.setResultType(0);
                    }
                    if (po.getBid() != null) {
                        Blessing byId = blessingService.findById(po.getBid() + "");
                        double v = byId.getMoney();
                        ProductOrderResult productOrderResult = new ProductOrderResult();
                        productOrderResult.setMoney(v);
                        productOrderResult.setType(1);
                        productOrderResult.setPrice(v);
                        productOrderResult.setName(byId.getName());
                        productOrderResult.setNum(po.getNum());
                        productOrderResults.add(productOrderResult);
                        money += po.getNum() * v;
                        count += po.getNum();
                        orders.setResultType(1);
                    }
                }
                Address byId = addressService.findById(orders.getAid());
                orders.setProductOrderResultsList(productOrderResults);
                orders.setAddress(byId);
                orders.setCountMoney(money + "");
                orders.setCount(count + "");
            }
            PageInfo<Orders> pageInfo = new PageInfo<>(all);
            Map<String, Object> map = new HashMap<>();
            map.put("orderList", all);
            map.put("pageNo", order.getPageNo());
            map.put("count", pageInfo.getTotal());
            return ConvenientResult.build(200, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 商品订单下单
     *
     * @param order 收货地址
     * @return Result结果集
     */
    @RequestMapping("/save")
    public ConvenientResult saveOrder(@RequestBody Orders order) {
        try {
            Integer save = ordersService.save(order);
            List<ProductOrder> productOrderList = order.getProductOrderList();
            for (ProductOrder productOrder : productOrderList
                    ) {
                productOrder.setOid(order.getId() + "");
                productOrderService.save(productOrder);
            }
            return ConvenientResult.build(200, "成功", save);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 更新订单状态
     *
     * @param order 订单信息
     * @return Result结果集
     */
    @RequestMapping("/update")
    public ConvenientResult updateOrder(@RequestBody Orders order) {
        try {
            Integer save = ordersService.update(order);
            Log log = new Log();
            log.setContent(JsonUtils.objectToJson(order));
            log.setCreateTime(DateUtils.getDate());
            log.setType(0);
            log.setUserId(order.getManagerId());
            System.out.println(JsonUtils.objectToJson(log));
            logService.save(log);
            return ConvenientResult.build(200, "成功", save);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 删除订单地址
     *
     * @param order 收货地址
     * @return Result结果集
     */
    @RequestMapping("/delete")
    public ConvenientResult deleteOrder(@RequestBody Orders order) {
        try {
            Integer save = ordersService.delete(order.getId() + "");
            Log log = new Log();
            log.setContent(JsonUtils.objectToJson(order));
            log.setCreateTime(DateUtils.getDate());
            log.setType(1);
            log.setUserId(order.getManagerId());
            logService.save(log);
            System.out.println(JsonUtils.objectToJson(log));
            return ConvenientResult.build(200, "成功", save);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * id查订单
     *
     * @param order 订单
     * @return Result结果集
     */
    @RequestMapping("/findOne")
    public ConvenientResult getOrderById(@RequestBody Orders order) {
        try {
            Orders st = ordersService.findById(order.getId() + "");
            ProductOrder productOrder = new ProductOrder();
            productOrder.setOid(st.getId() + "");
            List<ProductOrderResult> productOrderResults = new ArrayList<>();
            List<ProductOrder> all1 = productOrderService.findAll(productOrder);
            for (ProductOrder po : all1
                    ) {
                ProductOrderResult productOrderResult = new ProductOrderResult();
                if (po.getPid() != null) {
                    Product byId = productService.findById(po.getPid() + "");
                    productOrderResult.setMoney(byId.getMoney());
                    productOrderResult.setPrice(byId.getPrice());
                    productOrderResult.setName(byId.getName());
                    productOrderResult.setNum(po.getNum());
                    productOrderResults.add(productOrderResult);
                    st.setResultType(0);
                }
                if (po.getBid() != null) {
                    Blessing byId = blessingService.findById(po.getBid() + "");
                    double v = byId.getMoney();
                    productOrderResult.setMoney(v);
                    productOrderResult.setPrice(v);
                    productOrderResult.setName(byId.getName());
                    productOrderResult.setNum(po.getNum());
                    productOrderResults.add(productOrderResult);
                    st.setResultType(1);
                }
            }
            st.setProductOrder(all1);
            Address byId = addressService.findById(st.getAid());
            st.setProductOrderResultsList(productOrderResults);
            st.setAddress(byId);
            return ConvenientResult.build(200, "成功", st);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }


    /**
     * 更新订单状态
     *
     * @param order 订单信息
     * @return Result结果集
     */
    @RequestMapping("/refund")
    public ConvenientResult refund(@RequestBody Orders order) {
        try {
            order.setStatus("6");
            Integer save = ordersService.update(order);
            return ConvenientResult.build(200, "成功", save);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 订单列表
     *
     * @return Result结果集
     */
    @RequestMapping("/listOrder")
    public ConvenientResult getListOrder(String toDay, String yestDay, String weekDay, String monthDay) {
        try {
            Map<String, Object> resultMap = new HashMap<>(16);
            String[] split = toDay.split(" - ");
            List<Orders> between = ordersService.findBetween(split[0], split[1], null);
            resultMap.put("toDayVolume", between.size());
            Double money = 0.0;
            for (Orders order : between
                    ) {
                ProductOrder productOrder = new ProductOrder();
                productOrder.setOid(order.getId() + "");
                List<ProductOrder> all = productOrderService.findAll(productOrder);
                for (ProductOrder po : all
                        ) {
                    if (po.getPid() != null) {
                        Product byId = productService.findById(po.getPid() + "");
                        money += po.getNum() * byId.getMoney();
                    }
                    if (po.getBid() != null) {
                        Blessing byId = blessingService.findById(po.getBid() + "");
                        money += po.getNum() * byId.getMoney();
                    }
                }
            }
            resultMap.put("toDayMoney", money);
            List<CustomerInfo> all1 = customerInfoService.findAll(null);
            if (all1.size() != 0) {
                resultMap.put("toDayAverage", money / all1.size());
            } else {
                resultMap.put("monthDayAverage", 0);
            }
            String[] split1 = yestDay.split("-");
            List<Orders> between1 = ordersService.findBetween(split1[0], split1[1], null);
            resultMap.put("yestDayVolume", between1.size());
            Double money1 = 0.0;
            for (Orders order : between1
                    ) {
                ProductOrder productOrder = new ProductOrder();
                productOrder.setOid(order.getId() + "");
                List<ProductOrder> all = productOrderService.findAll(productOrder);
                for (ProductOrder po : all
                        ) {
                    if (po.getPid() != null) {
                        Product byId = productService.findById(po.getPid() + "");
                        money1 += po.getNum() * byId.getMoney();
                    }
                    if (po.getBid() != null) {
                        Blessing byId = blessingService.findById(po.getBid() + "");
                        money1 += po.getNum() * byId.getMoney();
                    }
                }
            }
            resultMap.put("yestDayMoney", money1);
            List<CustomerInfo> all2 = customerInfoService.findAll(null);
            resultMap.put("yestDayAverage", money1 / all2.size());
            if (all2.size() != 0) {
                resultMap.put("yestDayAverage", money1 / all2.size());
            } else {
                resultMap.put("monthDayAverage", 0);
            }
            String[] split2 = weekDay.split("-");
            List<Orders> between2 = ordersService.findBetween(split2[0], split2[1], null);
            resultMap.put("weekDayVolume", between2.size());
            Double money2 = 0.0;
            for (Orders order : between2
                    ) {
                ProductOrder productOrder = new ProductOrder();
                productOrder.setOid(order.getId() + "");
                List<ProductOrder> all = productOrderService.findAll(productOrder);
                for (ProductOrder po : all
                        ) {
                    if (po.getPid() != null) {
                        Product byId = productService.findById(po.getPid() + "");
                        money2 += po.getNum() * byId.getMoney();
                    }
                    if(po.getBid() != null){
                        Blessing byId = blessingService.findById(po.getBid() + "");
                        money2 += po.getNum() * byId.getMoney();
                    }
                }
                }
                resultMap.put("weekDayMoney", money2);
                List<CustomerInfo> all3 = customerInfoService.findAll(null);

                if (all3.size() != 0) {
                    resultMap.put("weekDayAverage", money2 / all3.size());
                } else {
                    resultMap.put("monthDayAverage", 0);
                }
                String[] split3 = monthDay.split("-");
                List<Orders> between3 = ordersService.findBetween(split3[0], split3[1], null);
                resultMap.put("monthDayVolume", between3.size());
                Double money3 = 0.0;
                for (Orders order : between3
                        ) {
                    ProductOrder productOrder = new ProductOrder();
                    productOrder.setOid(order.getId() + "");
                    List<ProductOrder> all = productOrderService.findAll(productOrder);
                    for (ProductOrder po : all
                            ) {
                        if (po.getPid() != null) {
                            Product byId = productService.findById(po.getPid() + "");
                            money3 += po.getNum() * byId.getMoney();
                        }
                        if (po.getBid() != null) {
                            Blessing byId = blessingService.findById(po.getBid() + "");
                            money3 += po.getNum() * byId.getMoney();
                        }
                    }
                }
                resultMap.put("monthDayMoney", money3);
                List<CustomerInfo> all4 = customerInfoService.findAll(null);
                if (all4.size() != 0) {
                    resultMap.put("monthDayAverage", money3 / all4.size());
                } else {
                    resultMap.put("monthDayAverage", 0);
                }
                return ConvenientResult.build(200, "成功", resultMap);
            } catch(Exception e){
                e.printStackTrace();
                return ConvenientResult.build(500, "系统错误", e.getStackTrace());
            }
        }

    }
